using FSM.IDal; 
using FSM.IBll; 
using FSM.Model; 
using SqlSugar; 
using System; 
using System.Collections.Generic; 
using System.Text;
using System.Text.RegularExpressions;

namespace FSM.Bll 
{ 
    public class SysCodeBll: ISysCodeBll 
    { 
        #region 模块 

        private readonly ISysCodeDal dal;
        private readonly ISysCodeSerialDal serialDal;
        public SysCodeBll(ISysCodeDal dal, ISysCodeSerialDal serialDal) 
        { 
            this.dal = dal;
            this.serialDal = serialDal;
        } 

        #endregion 
 
        #region 查询 
 
        /// <summary> 
        /// 根据键值查询单个信息 
        /// </summary> 
        /// <param name="pkid">键值</param> 
        /// <returns></returns> 
        public sys_code Get(string pkid) 
        { 
            return dal.GetById(pkid); 
        } 
 
        /// <summary> 
        /// 分页查询批量信息 
        /// </summary> 
        /// <param name="code_name">单据名称</param> 
        /// <param name="page">页码</param> 
        /// <param name="page_size">每页显示的条数</param> 
        /// <returns></returns> 
        public Tuple<List<sys_code>, int> ListPagin(string code_name, int page, int page_size) 
        { 
            ISugarQueryable<sys_code> queryable = dal.CreateQueryable(); 
            queryable = queryable.WhereIF(!string.IsNullOrEmpty(code_name),p => p.code_name == code_name); 
             
            PageModel pm = new PageModel 
            { 
                PageIndex = page, 
                PageSize = page_size 
            }; 
            Tuple<List<sys_code>, int> result = dal.GetPageListAndTotal(queryable, pm); 
            return result; 
        } 
 
        /// <summary> 
        /// 分页查询批量信息 
        /// </summary> 
        /// <param name="code_name">单据名称</param> 
        /// <returns></returns> 
        public List<sys_code> List(string code_name) 
        { 
            Expressionable<sys_code> queryable = Expressionable.Create<sys_code>(); 
            queryable = queryable.AndIF(!string.IsNullOrEmpty(code_name),p => p.code_name == code_name); 
             
            List<sys_code> result = dal.GetList(queryable.ToExpression()); 
            return result; 
        }

        /// <summary>
        /// 获得最新的流水号
        /// </summary>
        /// <param name="code_no">编号ID</param>
        /// <returns></returns>
        public string GetNewCode(string pkid)
        {
            sys_code code = Get(pkid);
            if (code == null) throw new Exception("请先设定对应的编号规则");
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("{pre}", code.code_prefx ?? "");
            dic.Add("{mid}", code.code_midfx ?? "");
            dic.Add("{lst}", code.code_lastfx ?? "");
            dic.Add("{year}", string.IsNullOrWhiteSpace(code.year_digit) ? "" : DateTime.Now.ToString(code.year_digit));
            dic.Add("{month}", string.IsNullOrWhiteSpace(code.month_digit) ? "" : DateTime.Now.ToString(code.month_digit));
            dic.Add("{day}", string.IsNullOrWhiteSpace(code.day_digit) ? "" : DateTime.Now.ToString(code.day_digit));
            string codeString = code.template;
            foreach (KeyValuePair<string, string> kv in dic)
            {
                if (codeString.Contains(kv.Key))
                {
                    codeString = codeString.Replace(kv.Key, kv.Value);
                }
            }
            string codePre = codeString.Replace("{serialno}", "");
            int num = 0;
            lock (this)
            {
                bool success = false;
                var serialModel = serialDal.GetSingle(p => p.code_pkid == code.pkid && p.code_pre == codePre);
                if (serialModel != null)
                {
                    num = serialModel.cur_serial_num.Value + 1;
                    serialModel.cur_serial_num = num;
                    success = serialDal.Update(serialModel);
                }
                else
                {
                    num++;
                    serialModel = new sys_code_serial()
                    {
                        code_pkid = code.pkid,
                        code_pre = codePre,
                        cur_serial_num = num
                    };
                    success = serialDal.Insert(serialModel);
                }
                if (success == false) throw new Exception("更新流水记录失败");
            }
            codeString = codeString.Replace("{serialno}", num.ToString().PadLeft(code.serial_digit.Value, '0'));
            return codeString;
        }
 
        #endregion 
 
        #region 提交 
 
        /// <summary> 
        /// 添加 
        /// </summary> 
        /// <param name="model">实体</param> 
        /// <returns></returns> 
        public bool Insert(sys_code model) 
        {
            model.pkid = Guid.NewGuid().ToString("N");
            model.create_date = DateTime.Now; 
            return dal.Insert(model); 
        } 
 
        /// <summary> 
        /// 更新 
        /// </summary> 
        /// <param name="model">实体</param> 
        /// <returns></returns> 
        public bool Update(sys_code model) 
        { 
            model.edit_date = DateTime.Now; 
            return dal.UpdateExcludeColumns(model, "creater", "create_date") == 1; 
        } 
 
        /// <summary> 
        ///  删除 
        /// </summary> 
        /// <param name="pkid">键值</param> 
        /// <returns></returns> 
        public bool Delete(params string[] pkid_arr) 
        { 
            return dal.Delete(pkid_arr); 
        } 
        #endregion 
    } 
} 
